import { useRef, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { PageHeader, Form, Input, Select, Button, message } from "antd";
import { Editor } from "@toast-ui/react-editor";

import { getTypeList } from "../redux/typeSlice";
import { typeOptionCreator } from "../utils/tools";
import { addIssue } from "../api/issue";

import styles from "../css/AddIssue.module.css";
import "@toast-ui/editor/dist/toastui-editor.css";
import "@toast-ui/editor/dist/i18n/zh-cn";

function AddIssue(props) {
  const [form] = Form.useForm();
  const editorRef = useRef();
  const { typeList } = useSelector((state) => state.type);
  const { userInfo } = useSelector((state) => state.user);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  /**
   * 提交问答的回调函数
   */
  async function handleAdd(issueInfo) {
    const content = editorRef.current.getInstance().getHTML();
    // 重新构建要提交给服务器的 issueInfo
    await addIssue({
      issueTitle: issueInfo.issueTitle,
      issueContent: content,
      userId: userInfo._id,
      typeId: issueInfo.typeId,
    });

    navigate("/");
    message.success("你的问题已经提交，审核通过后将会进行展示");
  }

  useEffect(() => {
    if (!typeList.length) {
      // 派发 action 来发送请求，获取到 类型数据 填充到状态仓库
      dispatch(getTypeList());
    }
  }, []);

  return (
    <div className={styles.container}>
      <PageHeader onBack={() => navigate("/")} title="发起提问" />

      <Form
        name="basic"
        autoComplete="off"
        initialValues={{
          issueTitle: "",
          typeId: "",
        }}
        form={form}
        onFinish={handleAdd}
      >
        {/* 问答标题 */}
        <Form.Item
          label="标题"
          name="issueTitle"
          rules={[{ required: true, message: "请输入标题" }]}
        >
          <Input placeholder="请输入标题" size="large" />
        </Form.Item>

        {/* 问题类型 */}
        <Form.Item
          label="问题分类"
          name="typeId"
          rules={[{ required: true, message: "请选择问题所属分类" }]}
        >
          <Select style={{ width: 200 }}>
            {typeOptionCreator(Select, typeList)}
          </Select>
        </Form.Item>

        {/* 问答内容 */}
        <Form.Item
          label="问题描述"
          name="issueContent"
          rules={[{ required: true, message: "请输入问题描述" }]}
        >
          <Editor
            initialValue=""
            previewStyle="vertical"
            height="500px"
            // EditType：所见即所得wysiwyg md文档markdown
            initialEditType="wysiwyg"
            // 使用快捷键
            useCommandShortcut={true}
            language="zh-CN"
            ref={editorRef}
          />
        </Form.Item>

        {/* 确认按钮 */}
        <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
          <Button size="large" type="primary" htmlType="submit">
            确认新增
          </Button>
          <Button
            size="large"
            type="link"
            htmlType="reset"
            className="resetBtn"
            style={{ marginLeft: "20px" }}
          >
            重置
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default AddIssue;
